package user

import (
	"context"
	"encoding/base64"
	"fmt"
	"strconv"

	"gitcode.com/G-YT/iHealth25/server/global"
	"gitcode.com/G-YT/iHealth25/server/model/common/response"
	userReq "gitcode.com/G-YT/iHealth25/server/model/user/request"
	userRes "gitcode.com/G-YT/iHealth25/server/model/user/response"
	"gitcode.com/G-YT/iHealth25/server/utils"
	"github.com/gin-gonic/gin"
	"github.com/silenceper/wechat/cache"
	"github.com/silenceper/wechat/v2"
	miniConfig "github.com/silenceper/wechat/v2/miniprogram/config"
	"github.com/silenceper/wechat/v2/miniprogram/qrcode"
	"go.uber.org/zap"
)

const (
	MINI_APP_LATEST_ID     = "wxae78daad54f99c72"
	MINI_APP_LATEST_SECRET = "e0558655a487724bfcf14640944b6df0"
)

type UserApi struct {
}

// GetUserData 获取用户信息
// @Tags User
// @Summary 用id查询用户
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query user.User true "用id查询用户"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /api/user/getUserDate [get]
func (u *UserApi) GetUserData(c *gin.Context) {
	id := c.Query("id")
	ID, _ := strconv.Atoi(id)
	//ID := utils.GetUserID(c)
	if ResUser, err := UserService.GetUserInfo(uint(ID)); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithDetailed(ResUser, "获取成功", c)
	}
}

// UpdateUser 更新User
// @Tags User
// @Summary 更新User
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body user.user true "更新User"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /api/user/updateUser [put]
func (u *UserApi) UpdateUser(c *gin.Context) {
	var us userReq.UpdateUser
	err := c.ShouldBindJSON(&us)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if us.Avatar != "" {
		a := utils.CreateAudit(global.GVA_CONFIG.Audit.Objs)
		AvatarStatus, _ := a.AuditImageUrl(us.Avatar)
		if AvatarStatus == false {
			response.FailWithMessage("图片违规,请重新上传", c)
			return
		}
	}
	if err := UserService.UpdateUser(us.ID, us); err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		err = UserService.AddPoints(us.ID, 10, 5)
		response.OkWithMessage("更新成功", c)
	}
}

// GetUserInviteLink 获取邀请链接
// @Tags User
// @Summary 获取邀请链接
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query user.User true "获取邀请链接"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /api/user/getInviteLink [post]
func (u *UserApi) GetUserInviteLink(c *gin.Context) {
	userId := utils.GetUserID(c)
	// 获取系统配置参数
	config, _ := appConfigService.GetRedisByField([]string{"version_num", "app_url", "customer_service_wechat"})
	// 获取统计数据
	CountData, _ := appConfigService.GetCountRedis([]string{"users_total", "pv_total"})
	//usersTotal, _ := strconv.ParseFloat(CountData["users_total"].(string), 64)
	//heat := fmt.Sprintf("%f", usersTotal)
	//usersTotal := CountData["users_total"]
	//pvTotal, _ := strconv.ParseUint(CountData["pv_total"].(string), 10, 0)
	// 获取未读消息数
	UnReadMessageNumber, _ := MessageService.GetUnReadMessageNumber(userId)
	if user, err := UserService.GetUserInfo(userId); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取用户信息失败!", c)
	} else {
		response.OkWithDetailed(userRes.InviteLinkResponse{
			StewardID:             user.StewardID,
			ID:                    user.ID,
			Heat:                  CountData["users_total"].(string),
			UsersNumber:           CountData["pv_total"].(string),
			UnReadMessageNumber:   uint(UnReadMessageNumber),
			CustomerServiceWechat: config["customer_service_wechat"],
			AppUrl:                config["app_url"],
			VersionNum:            config["version_num"],
		}, "获取成功", c)
	}
}

// ChangePassword 用户修改密码
// @Tags User
// @Summary 用户修改密码
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query user.User true "用id查询用户"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /api/user/changePassword [post]
func (u *UserApi) ChangePassword(c *gin.Context) {
	var uc userReq.ChangePassword
	err := c.ShouldBindJSON(&uc)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	// 判断两次密码是否相同
	if uc.Password != uc.NewPassword {
		response.FailWithMessage("新密码与确认密码不同", c)
		return
	}
	id := utils.GetUserID(c)
	userInfo, _ := UserService.FindUserByID(id)
	// 判断短信验证码
	key := "Sms:Phone:Code:" + userInfo.Phone
	captcha, _ := global.GVA_REDIS.Get(context.Background(), key).Result()
	if captcha != uc.Code {
		response.Result(200, "", "验证码有误,请核实!", c)
		return
	}
	err = UserService.ChangePassword(id, uc.NewPassword)
	if err != nil {
		global.GVA_LOG.Error("修改失败!", zap.Error(err))
		response.FailWithMessage("修改失败", c)
		return
	}
	response.OkWithMessage("修改成功", c)
}

// MyThoughts 我的心得
// @Tags User
// @Summary 我的心得
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /user/myThoughts [get]
func (u *UserApi) MyThoughts(c *gin.Context) {
	id := utils.GetUserID(c)
	if list, err := CircleService.GetCircleInfoListByUid(id); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.Result(200, list, "获取成功", c)
	}
}

// SubmitOpenVip 提交开通&续费会员
// @Tags User
// @Summary 提交开通&续费会员
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /user/submitOpenVip [get]
func (u *UserApi) SubmitOpenVip(c *gin.Context) {
	id := utils.GetUserID(c)
	// 查询是否存在待审核申请
	record, _ := UserService.FindLastRecordByWhere(id)
	if int(record.Status) == 1 || int(record.Status) == 3 {
		response.Result(200, "", "存在未通过审核的申请,请联系客服!", c)
		return
	}
	if err := UserService.CreateOpenRecord(id); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("申请失败", c)
	} else {
		response.Result(200, "", "申请成功", c)
	}
}

// GetUserByVipLevel 根据会员等级获取用户信息示例
func (u *UserApi) GetUserByVipLevel(c *gin.Context) {
	vip_type := c.Query("vip_type")
	if err := UserService.GetUserByVipLevel(vip_type); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("申请失败", c)
	} else {
		response.Result(200, "", "申请成功", c)
	}
}

// GetUserDivisionInfo 获取用户成就信息
func (u *UserApi) GetUserDivisionInfo(c *gin.Context) {
	id := utils.GetUserID(c)
	info, err := UserService.GetUserDivisionInfo(id)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.Result(200, info, "获取成功", c)
	}
}

// GetUserDivisionRank 获取用户段位排行榜
func (u *UserApi) GetUserDivisionRank(c *gin.Context) {
	rank, err := UserService.GetUserDivisionRank()
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.Result(200, rank, "获取成功", c)
	}
}

// GetCountWeeklyPoints 获取用户一周积分
func (u *UserApi) GetCountWeeklyPoints(c *gin.Context) {
	userID := utils.GetUserID(c)
	data, err := UserService.GetCountWeeklyPoints(userID)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.Result(200, data, "获取成功", c)
	}
}

// TranslateTable 迁移用户数据
func (u *UserApi) TranslateTable(c *gin.Context) {
	go func() {
		_ = UserService.TranslateTable()
		fmt.Print("携程内运行转移操作")
	}()
	response.Result(200, "", "携程内运行转移操作", c)
}

// GetAccessToken 获取微信AccessToken
//func (u *UserApi) GetAccessToken(c *gin.Context) {
//	data, err := UserService.GetAccessToken()
//	if err != nil {
//		global.GVA_LOG.Error("获取失败!", zap.Error(err))
//		response.FailWithMessage("获取失败", c)
//	} else {
//		response.Result(200, data, "获取成功", c)
//	}
//}

// GenerateQRCode 生成小程序二维码
func (u *UserApi) GenerateQRCode(c *gin.Context) {
	// 接参
	var uq userReq.QRCode
	err := c.ShouldBindJSON(&uq)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	StewardID := strconv.FormatUint(uint64(uq.StewardID), 10)
	InviteUserID := strconv.FormatUint(uint64(uq.InviteUserID), 10)
	// 生成唯一文件名
	// 初始化 Wechat 实例
	wc := wechat.NewWechat()
	//这里本地内存保存access_token，也可选择redis，memcache或者自定cache
	memory := cache.NewMemory()
	//token, _ := requestToken(MINI_APP_LATEST_ID, MINI_APP_LATEST_SECRET)
	cfg := &miniConfig.Config{
		AppID:     MINI_APP_LATEST_ID,
		AppSecret: MINI_APP_LATEST_SECRET,
		Cache:     memory,
	}
	//officialAccount := wc.GetOfficialAccount(cfg)
	mini := wc.GetMiniProgram(cfg)
	qcode := mini.GetQRCode()
	f := false
	res, err := qcode.GetWXACodeUnlimit(qrcode.QRCoder{
		Page: "pages/index/login",
		//Path: "?pathName=/race/pages/group&id=58",
		CheckPath: &f,
		Width:     300,
		Scene:     "steward_id=" + StewardID + "&invite_user_id=" + InviteUserID,
		//AutoColor:  false,
		//LineColor:  nil,
		//IsHyaline:  false,
		//EnvVersion: "",
	})
	if err != nil {
		global.GVA_LOG.Error("生成失败!", zap.Error(err))
		response.FailWithMessage("生成失败", c)
	} else {
		// 新增base64编码转换
		base64Str := base64.StdEncoding.EncodeToString(res)
		response.Result(200, base64Str, "生成成功", c)
	}
	//png, err := os.Create("data.png")
	//_, err2 := png.Write(res)
	//
	//if err2 != nil {
	//	log.Fatal(err2)
	//}
	// 上传OSS
}

// UrgentCardQRCode 生成急救卡太阳码
func (u *UserApi) UrgentCardQRCode(c *gin.Context) {
	// 接参
	var us userReq.SunCode
	err := c.ShouldBindJSON(&us)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	ID := strconv.FormatUint(uint64(us.ID), 10)
	// 生成唯一文件名
	// 初始化 Wechat 实例
	wc := wechat.NewWechat()
	//这里本地内存保存access_token，也可选择redis，memcache或者自定cache
	memory := cache.NewMemory()
	//token, _ := requestToken(MINI_APP_LATEST_ID, MINI_APP_LATEST_SECRET)
	cfg := &miniConfig.Config{
		AppID:     MINI_APP_LATEST_ID,
		AppSecret: MINI_APP_LATEST_SECRET,
		Cache:     memory,
	}
	//officialAccount := wc.GetOfficialAccount(cfg)
	mini := wc.GetMiniProgram(cfg)
	qcode := mini.GetQRCode()
	f := false
	res, err := qcode.GetWXACodeUnlimit(qrcode.QRCoder{
		Page: "subpackages/wode/card/form",
		//Path: "?pathName=/race/pages/group&id=58",
		CheckPath: &f,
		Width:     300,
		Scene:     "id=" + ID,
		//AutoColor:  false,
		//LineColor:  nil,
		//IsHyaline:  false,
		//EnvVersion: "",
	})
	if err != nil {
		global.GVA_LOG.Error("生成失败!", zap.Error(err))
		response.FailWithMessage("生成失败", c)
	} else {
		// 新增base64编码转换
		base64Str := base64.StdEncoding.EncodeToString(res)
		response.Result(200, base64Str, "生成成功", c)
	}
	//png, err := os.Create("data.png")
	//_, err2 := png.Write(res)
	//
	//if err2 != nil {
	//	log.Fatal(err2)
	//}
	// 上传OSS
}
